package com.cwj.thread;

import sun.misc.Contended;

import java.util.AbstractQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author chenwujie
 * @date 2021-03-05 10:51
 */
public class VolatileTest {
    private volatile Object obj;
    public static void main(String[] args) {
        VolatileTest volatileTest = new VolatileTest();
        volatileTest.newInstance();

        BlockingDeque<Runnable> runnables = new LinkedBlockingDeque<>();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 10, TimeUnit.SECONDS, runnables);

        for (int i = 0; i < 1000; i++) {
            Runnable runnable = new Runnable() {
                @Override public void run() {
                    long n1 = System.currentTimeMillis();
                    for (int i = 0; i < 999999999; i++) {
                        V1 v1 = new V1();
                        v1.x++;
                    }
                    long n2 = System.currentTimeMillis();
                    for (int i = 0; i < 999999999; i++) {
                        V2 v2 = new V2();
                        v2.x++;
                    }
                    long n3 = System.currentTimeMillis();
                    System.out.println((n2 - n1) > n3 - n2);
                }
            };
            executor.execute(runnable);
        }
    }

    public void newInstance(){
        this.obj = new Object();
    }

    private static class V1{
        volatile long x;
    }
    @Contended
    private static class V2{
        volatile long x;
    }



}
